<template>
    <div class="search">
        <el-select v-model="searchKey" filterable remote placeholder="请输入内容搜索" :remote-method="remoteMethod"
            :loading="listloading" @change="searchChange" clearable @clear="clearSearchKey">
            <el-option v-for="item in searchOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
    </div>
    <el-button type="primary" @click="addProject">添加项目</el-button>
    <div class="export">
        <el-button  @click="exportExcel">
            <template #icon>
                <svg>
                    <use class="icon" xlink:href="#icon-excel"></use>
                </svg>
            </template>
            <template #default>导出Excel</template>
        </el-button>
    </div>
    <div class="table">
        <el-table :data="tableData" border style="width: 100%" class="usertable" :loading="tableloading">
            <el-table-column prop="headimgurl" label="头像" align="center">
                <template v-slot="{ row }">
                    <el-avatar :src="row.headimgurl" size="large" shape="square"></el-avatar>
                </template>
            </el-table-column>
            <el-table-column prop="name" label="姓名" align="center" />
            <el-table-column prop="class" label="班级" align="center" />
            <el-table-column prop="description" label="学历" align="center" />
            <el-table-column prop="productUrl" label="项目" align="center" />
            <el-table-column prop="cTime" label="创建时间" align="center" />
            <el-table-column prop="" label="操作" align="center">
                <template v-slot="{ row }">
                    <el-button type="success" circle :icon="View" v-has:read="userauthority" />
                    <el-button type="primary" circle :icon="Edit" v-has:edit="userauthority" @click="edit(row)" />
                    <el-button type="danger" circle :icon="Delete" v-has:delete="userauthority" @click="del(row)" />
                </template>

            </el-table-column>
        </el-table>
    </div>
    <el-pagination background layout="prev, pager, next" @current-change="pageChange" :page-size="pageSize"
        :current-page="currentPage" :total="total" />
    <qf-dialog :visible="dialogFormVisible" :dialogData="dialogData" @sureClick="sureClick" @closeClick="closeClick"
        @cancleClick="cancleClick" :dialogTitle="dialogTitle">
        <template v-slot:upload>
            <el-upload class="avatar-uploader" method="post" name="headimgurl" action="/api/students/uploadStuAvatar"
                v-loading="imgloading" :show-file-list="false" :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                </el-icon>
            </el-upload>
        </template>
    </qf-dialog>
</template>
<script setup>
import { ref, onMounted, reactive } from 'vue'
import * as api from '@/api/index.js'
import { useLogin } from '../../../../store/cart'
import { storeToRefs } from 'pinia'
//引入导出excel的插件
import qee from 'qf-export-excel'
//引入弹窗组件
import qfDialog from '../../../../components/dialog/index.vue'
import {
    Delete,
    Edit,
    View,
    Plus
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
//默认页码
let currentPage = ref(1)
let changeLogin = useLogin()
let changeUse = useLogin()
let { userInfo, btn } = storeToRefs(changeUse)
//搜索的数据结构
let searchOptions = ref([])
//搜索的关键字
let searchKey = ref('')
//搜索的加载动画
let listloading = ref(true)
//搜索框输入后触发的方法
let remoteMethod = async (t) => {
    //t是输入框输入的内容
    //判断输入框内是否有内容
    if (!t) {
        return
    }
    //开启搜索框加载动画
    listloading.value = true
    try {
        //发送搜素数据的请求
        let res = await api.seachStudentMsg(t)
        //将搜索到的联想数据映射到搜索框内
        let repeatDates = res.data.data.map(item => ({ value: item.name }))
        let norepeatDates = []
        //对获取到的搜索内容进行去重
        for (var i = 0; i < repeatDates.length; i++) {
            let flag = true;
            for (var j = 0; j < norepeatDates.length; j++) {
                if (repeatDates[i].value === norepeatDates[j].value) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                norepeatDates.unshift(repeatDates[i])
            }
        }
        //去重后进行去重操作
        searchOptions.value = norepeatDates
        listloading.value = false
    } catch (e) {
        // console.log(e);
        listloading.value = false
    }
}
//清空关键字后的方法
let clearSearchKey = () => {
    currentPage.value = 1
}
//用户选择了输入框的值后，触发方法
let searchChange = async (key, page = 1, count = 10) => {
    tableloading.value = true
    searchOptions.value = []
    //获取点选的值
    try {
        let res = await api.seachStudentMsg(searchKey.value, count, page)
        //将搜索的结果赋值给表格 
        tableData.value = res.data.data
        tableloading.value = false
        setPageNation(res.data.total)
    } catch (e) {
        console.log(e);
        tableloading.value = false

    }
}

let tableData = ref([])
let tableloading = ref(true)
let userauthority = ref([])
userauthority.value = btn.value
let vHas = {
    mounted(el, binding) {
        let a = binding.arg
        let b = binding.value
        let c = b.includes(a)
        if (!c) {
            el.style.cursor = 'not-allowed'
            el.disabled = true
        }
    }
}

//封装方法获取表格数据
let getStuList = async (page, count, classes) => {
    tableloading.value = true
    try {
        let res = await api.getAllStudentMsg(page, count, classes)
        console.log(res);
        tableData.value = res.data.data
        tableloading.value = false
        setPageNation(res.data.total)
    } catch (e) {
        tableloading.value = false
        // console.log(e);
    }
}
onMounted(() => {
    getStuList()
})

//分页处理
//一页展示多少条
let pageSize = ref(10)
//分页器的total属性
let total = ref(10)
//变更页面的时候
let payCount = ref()
let pageChange = (current) => {
    console.log(current);
    payCount.value = current
    // console.log();
    //判断是否有搜索关键字，如果有应该更新搜索的分页结果
    //否则拉取列表全部的数据
    currentPage.value = current
    if (searchKey.value) {
        searchChange(null, current)
    } else {
        getStuList(current)
    }
}
//专门修改分页器内容的方法
let setPageNation = (totalCount = 100, count = 10, currentPage = 1) => {
    total.value = totalCount
    pageSize.value = 10
}

//弹窗相关代码
let dialogFormVisible = ref(false)
let dialogData = reactive({
    name: {
        label: '姓名',
        value: ''
    },
    productUrl: {
        label: '项目地址',
        value: ''
    },
    class: {
        label: '班级',
        value: ''
    },
    age: {
        label: '年龄',
        value: ''
    },
    city: {
        label: '城市',
        value: ''
    },
    degree: {
        label: '学历',
        value: ''
    },
    description: {
        label: '描述',
        value: ''
    },
})
//表单校验成功后触发的逻辑
let sureClick = async (a) => {
    // dialogFormVisible.value=false
    // console.log(dialogData);
    let obj = {
        headimgurl: '',
        class: dialogData.class.value,
        productUrl: dialogData.productUrl.value,
        age: dialogData.age.value,
        name: dialogData.name.value,
        city: dialogData.city.value,
        degree: dialogData.degree.value,
        description: dialogData.description.value,
    }
    console.log(obj);
    try {
        let apiMethod = null
        let message = ''
        switch (dialogTitle.value) {
            case '增加学员信息':
                //判断是否上传头像，如果上传了，那么就携带到obj中
                apiMethod = api.addStudentMsg;

                obj.sId ? delete obj.sId : '';
                message = '添加成功'
                break;
            case '编辑信息':
                apiMethod = api.editStudentMsg
                //给obj添加sid属性
                obj.sId = sId.value
                message = '修改成功'
        }
        obj.headimgurl = headimgurl.value ? headimgurl.value : ''
        let res = await apiMethod(obj)
        //提示添加成功
        ElMessage({
            message,
            type: 'success',
        })
        //关闭dialog
        dialogFormVisible.value = false
        //清空表单
        a.value.resetFields()
        //更新列表
        getStuList()
    } catch (e) {
        ElMessage({
            message: e.toString(),
            type: 'error',
        })
    }
}
//点击取消按钮后触发的逻辑
let cancleClick = () => {
    dialogFormVisible.value = false
}
//点击添加项目按钮后执行的逻辑
let addProject = () => {
    // console.log(1);
    dialogTitle.value = '增加学员信息'
    dialogFormVisible.value = true
}
//用户点击空白或者叉号触发的逻辑
let closeClick = () => {
    dialogFormVisible.value = false
    let keys = Object.keys(dialogData)
    keys.forEach(key => {
        dialogData[key].value = ''
    })
    //清空头像的回显
    imageUrl.value = ''
}
let dialogTitle = ref()
//声明一个变量，存储sID,便于编辑的时候传递给后端
let sId = ref('')
//点击编辑按钮触发的事件
let edit = async (row) => {
    //修改标题
    dialogTitle.value = '编辑信息'
    // dialogData = row
    let keys = Object.keys(dialogData)
    console.log(keys);
    keys.forEach(key => {
        dialogData[key].value = row[key]
    })
    dialogFormVisible.value = true
    sId.value = row.sId
    console.log(sId.value);
    //点击编辑时，将这条数据中的headimgurl数据回显给全局的headimgurl
    headimgurl.value = row.headimgurl
    //回显
    imageUrl.value = row.headimgurl
}

//上传文件
//一个保存上传地址的变量
let imageUrl = ref()
//声明一个headimgurl变量，用于将参数在表单dialog通过的时候，一并提交给后台
let headimgurl = ref('')
//上传成功触发的逻辑
let handleAvatarSuccess = (res, uploadFile) => {
    console.log(res);
    if (res.msg) {
        ElMessage({
            type: 'success',
            message: res.msg
        })
        headimgurl.value = res.headimgurl
    } else {
        ElMessage({
            type: 'error',
            message: res.msg
        })
    }
    imgloading.value = false
    imageUrl.value = URL.createObjectURL(uploadFile.raw)
}
let imgloading = ref(false)
//上传前的逻辑
let beforeAvatarUpload = (rawFile) => {

    let accepType = ['image/jpeg', 'image/jpg', 'image/png']
    //判断当前上传的文件按类型是否包含于accepType中
    let isAccept = accepType.includes(rawFile.type)
    if (!isAccept) {
        ElMessage.error('上传的文件类型只能是jpeg、jpg和png,您当前上传的文件类型是' + rawFile.type)
        return false
    } else if (rawFile.size / 1024 / 1024 > 1) {
        ElMessage.error('上传文件的大小不能大于1mb')

        return false
    }
    imgloading.value = true
    return true
}


//点击删除触发的事件
let del = (row) => {
    ElMessageBox.confirm('此操作将永久删除这条数据,是否继续', '警告', {
        confirmButtonText: "确定",
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(async () => {
            try {
                let res = await api.delStudentMsg(row.sId)
                ElMessage({
                    type: 'success',
                    message: '删除成功'
                })
                getStuList(payCount.value)
            } catch (e) {
                console.log(e);
            }
        })
        .catch(() => {
            ElMessage({
                type: 'warning',
                message: '已取消'
            })
        })

}
let exportExcel = ()=>{
    let titleList = [
        {
            title:'姓名',
            key:'name'
        },
        {
            title:'年龄',
            key:'age'
        },
        {
            title:'头像地址',
            key:'headimgurl'
        },
        {
            title:'学历',
            key:'degree'
        },
        {
            title:'班级',
            key:'class'
        },
    ]
    qee(titleList,tableData.value,'项目数据')
}
</script>
<script>
export default {
    meta: {
        title: 'xyxmgl', name: '学员项目管理',
        iconfont: '#icon-kaoqin2'
    }
}


</script>
<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
